//
//  MHChangePassViewController.m
//  MHO
//
//  Created by papo on 3/3/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHChangePassViewController.h"
#import "MHNavibarView.h"
#import "Lib.h"
#import "Account.h"

@interface MHChangePassViewController ()
{
    MHNavibarView* navibarView;
    UITextField* activeField;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITextField *currentPassword;
@property (weak, nonatomic) IBOutlet UITextField *nPasswordText;
@property (weak, nonatomic) IBOutlet UITextField *renewPassword;
@end

@implementation MHChangePassViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    navibarView = [MHNavibarView createWithTitle:@"Đổi mật khẩu" leftButton:nil rightButton:@"" searchButton:NO];
    [self.view addSubview:navibarView];
    [navibarView setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:nil search:nil];
    [navibarView setRootViewController:self];
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)];
    [self.view addGestureRecognizer:tap];
    
    [self registerForKeyboardNotifications];
    
    [_scrollView setContentSize:CGSizeMake(320, 500)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
    
    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    CGRect tRect = activeField.frame;
    tRect.origin.y -= aRect.size.height - _scrollView.frame.origin.y - tRect.size.height;
    tRect.origin.x = 0;
    
    if (tRect.origin.y < 0) {
        tRect.origin.y = 0;
    }
//    if (!CGRectContainsPoint(aRect, activeField.frame.origin) )
    {
        [self.scrollView setContentOffset:tRect.origin animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    _scrollView.contentInset = contentInsets;
    _scrollView.scrollIndicatorInsets = contentInsets;
}

- (void)tapGesture:(UIGestureRecognizer*)gesture {
    [self.scrollView endEditing:YES];
}

#pragma mark - TextField Delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    activeField = textField;
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    activeField = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}


- (void) leftButtonPressed:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)acceptButtonPressed:(id)sender {
    NSString* currentPass = _currentPassword.text;
    NSString* newPass = _nPasswordText.text;
    NSString* renewPass = _renewPassword.text;
    
    if (strCheckNull(currentPass).length == 0) {
        [Lib showMessage:@"Bạn chưa nhập mật khẩu hiện tại" title:@""];
        [_currentPassword becomeFirstResponder];
    }
    else if (strCheckNull(newPass).length == 0) {
        [Lib showMessage:@"Bạn chưa nhập mật khẩu mới" title:@""];
        [_nPasswordText becomeFirstResponder];
    }
    else if (strCheckNull(renewPass).length == 0) {
        [Lib showMessage:@"Bạn chưa nhập lại mật khẩu mới" title:@""];
        [_renewPassword becomeFirstResponder];
    }
    else if (![newPass isEqualToString:renewPass]){
        [Lib showMessage:@"Mật khẩu mới không trùng nhau!" title:@""];
        [_currentPassword becomeFirstResponder];
    }else {
        [Lib showLoadingView];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            ServiceResult* result = [Account changePassword:currentPass newPass:newPass];
            dispatch_async(dispatch_get_main_queue(), ^{
                [Lib removeLoadingView];
                [Lib showMessage:result.message title:@""];
            });
        });
    }
}

@end
